package com.css.fxfzfxqh.modules.reportTemplate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.modules.reportTemplate.entity.Template;
import com.css.fxfzfxqh.modules.reportTemplate.repository.TemplateRepository;
import com.css.fxfzfxqh.modules.reportTemplate.service.TemplateService;
import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.util.FileUploadUtil;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2023年10月24日  10:30
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    TemplateRepository templateRepository;
    @Resource
    SUserService sUserService;
    @Resource
    AttachmentInfoRepository attachmentInfoRepository;
    @Resource
    SysRoleService sysRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Template template) {
        String userID = PlatformObjectUtils.isNotEmpty(PlatformSessionContext.getUserID())?PlatformSessionContext.getUserID():"80cd530287e54c6788925adf2dfc9da1";
        SUser user = getUser(userID);
        template.setId(UUIDGenerator.getUUID());
        template.setCreateUserId(userID);
        template.setCreateTime(new Date());
        template.setCreateUserName(user.getUserName());
        templateRepository.save(template);
    }

    private SUser getUser(String userID){
        String sUser = sUserService.getSUser(userID);
        return  CreateGson.createGson().fromJson(sUser, SUser.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(String id, String attachId,String name,String templateDesc) {
        templateRepository.update(id,attachId,name,templateDesc);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        Template template = templateRepository.findById(id);
        if(StringUtils.isNotBlank(template.getAttachId())){
            attachmentInfoRepository.deleteFile(template.getAttachId());
        }
        templateRepository.delete(id);
    }

    @Override
    public void download(String id, HttpServletResponse response) {
        Template template = templateRepository.findById(id);
        if(StringUtils.isNotBlank(template.getAttachId())){
            AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(template.getAttachId());
            if(PlatformObjectUtils.isNotEmpty(attach)){
                //FileUploadUtil.download(attach.getFileDirId()+ File.separator+attach.getAttachPath(),res);
                try {
                    //请求头的模板名为中文
                    String file_name = URLEncoder.encode(attach.getAttachName(), "UTF-8");
                    response.setHeader("content-Type", "application/vnd.ms-excel");
                    response.setHeader("Content-disposition", "attachment;fileName=" + file_name);
                    response.setContentType("application/x-download");
                    //获取文件的路径
                    String path = attach.getFileDirId()+ File.separator+attach.getAttachPath();
                    //路径名转换中文
                    String filePath = URLDecoder.decode(path, "utf-8");
                    FileInputStream inputStream = new FileInputStream(filePath);
                    OutputStream outputStream = response.getOutputStream();
                    byte[] bytes = new byte[65536];
                    int len;
                    while ((len = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * w
     * 01确定评估-设定烈度.docx
     * 02确定评估-四个概率水准docx
     * 03确定评估-设定地展影响场,docx
     * 04概率评估-发生概率docx
     * 05生命线评估-设定烈度.docx
     * 06生命线评估-设定地展影响场.docx
     * 01: JZW-QD-LD-0102: JZW-QD-GL-02
     * 03: JZW-QD-YXC-03
     * 04: JZW-GL-FS-04
     * 05: SMX-LD-05
     * 06: SMX-YXC-06
     */
    @Override
    public RestResponse getTemplateNum(String reportType, String input) {
        String num = "";
        if("10000001".equals(reportType)){
            if("1000000101".equals(input)){
                num = "JZW-QD-LD-01";
            }else if("1000000102".equals(input)){
                num = "JZW-QD-GL-02";
            }else if("1000000103".equals(input)){
                num = "JZW-QD-YXC-03";
            }
        }else if("10000002".equals(reportType)){
            if("1000000201".equals(input)){
                num = "JZW-GL-FS-04";
            }
        }else if("10000003".equals(reportType)){
            if("1000000301".equals(input)){
                num = "SMX-LD-05";
            }else if("1000000302".equals(input)){
                num = "SMX-YXC-06";
            }
        }
        return RestResponse.succeed(num);
    }

    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, String num,String name) {
        String userId = PlatformObjectUtils.isNotEmpty(PlatformSessionContext.getUserID())?PlatformSessionContext.getUserID():"80cd530287e54c6788925adf2dfc9da1";
        String user = sUserService.getSUser(userId);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for(int i=0;i<maps.size();i++){
            Map map = maps.get(i);
            roles.append(map.get("roleCode")+",");
        }
        String allRole = roles.toString();
        //国家级
        if(!allRole.contains(FxfzConstants.QH_GJ_ROLE)){
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("Message","无权限");
            return stringObjectHashMap;
        }
        return templateRepository.getPage(curPage, pageSize, num,name);
    }

    @Override
    public Template findById(String id) {
        return templateRepository.findById(id);
    }

    @Override
    public int getByTemplateNum(String num) {
        return templateRepository.getByTemplateNum(num);
    }

    @Override
    public int getByTemplateName(String name,String num) {
        Template template = templateRepository.getByTemplateName(name);
        if(template!=null){
            if(StringUtils.isNotBlank(num) && num.equals(template.getNum())){
                return 0;
            }
            return 1;
        }
        return 0;
    }

}
